﻿
#include "ConstantBufferCollection.h"
#include "ConstantBuffer.h"

#include <System/Diagnostics/Debug.h>

using namespace Riccsson::Xna::Framework::Graphics;

ConstantBufferCollection::ConstantBufferCollection(ShaderStage stage, int maxBuffers)
{
	
	Riccsson::System::Diagnostics::Debug::WriteLine("ConstantBufferCollection() is calling.");
	_stage = stage;
	_buffers = new Riccsson::System::Array<GC_PTR<ConstantBuffer>>(maxBuffers);
	_valid = 0;
}

// TODO: Insert a GET SET Method instead.
//public: ConstantBuffer ConstantBufferCollection::this[int index]
//{
//	get { return _buffers[index]; }
//	set
//	{
//		if (_buffers[index] == value)
//			return;
//
//		if (value != null)
//		{
//			_buffers[index] = value;
//			_valid |= 1 << index;
//		}
//		else
//		{
//			_buffers[index] = null;
//			_valid &= ~(1 << index);
//		}
//	}
//}

void ConstantBufferCollection::Clear()
{
	_valid = 0;
}

#if DIRECTX
void ConstantBufferCollection::SetConstantBuffers(GraphicsDevice device)
#elif OPENGL || PSM
void ConstantBufferCollection::SetConstantBuffers(GraphicsDevice device, int shaderProgram)
#else
void ConstantBufferCollection::SetConstantBuffers(GC_PTR<GraphicsDevice> device, int shaderProgram)
#endif
{
	// If there are no constant buffers then skip it.
	if (_valid == 0)
		return;

	var valid = _valid;

	for (var i = 0; i < _buffers->Length; i++)
	{
		var buffer = _buffers->at(i);
		if (buffer != null)
		{
#if DIRECTX
			buffer.Apply(device, _stage, i);
#elif OPENGL || PSM
			buffer.Apply(device, shaderProgram);
#endif
		}

		// Early out if this is the last one.
		valid &= ~(1 << i);
		if (valid == 0)
			return;
	}
}